package com.bible.fire.service;

import com.bible.fire.R;
import com.bible.fire.local.AppContext;
import com.bible.fire.local.RuntimeContext;
import com.bible.fire.pad.activity.surface.DesktopActivity;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;

public class RestartAppService extends Service {
	
	private String TAG = RestartAppService.class.getSimpleName();

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG, "start to run app service");
		AlertDialog.Builder builder = new AlertDialog.Builder(RestartAppService.this);
		AlertDialog d = builder.create();
		//d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
		d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		//builder.setMessage("很抱歉,程序出现异常,即将退出.");
		//builder.setTitle("提示");
		View view = View.inflate(RestartAppService.this, R.layout.restart_app_tip, null);
		d.setView( view );
		View btn = view.findViewById( R.id.btn_restartApp );
		btn.setOnClickListener(new OnClickListener() {
	         @Override
	         public void onClick(View v) {
	        	 Log.d(TAG, "start to end app....");
	        	 Intent intent = new Intent();  
	             // 参数1：包名，参数2：程序入口的activity
	        	 Context gContext = AppContext.getContext();
	             intent.setClassName(gContext.getPackageName(), DesktopActivity.class.getName()); 
	             
	             PendingIntent restartIntent = PendingIntent.getActivity( gContext, 0,  
	                     intent, Intent.FLAG_ACTIVITY_NEW_TASK); 
	             AlarmManager mgr = (AlarmManager)gContext.getSystemService(Context.ALARM_SERVICE);  
	             mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用  
	             RuntimeContext.finishRuntimeApp(); // 自定义方法，关闭当前打开的所有avtivity
	         }
	     });
		/*
			builder.setPositiveButton("确认", new OnClickListener(){
			   @Override
			   public void onClick(DialogInterface dialog, int which) {
				    dialog.dismiss();
			   }
			}); */
		d.show();
		return START_NOT_STICKY;
	}
	
	public void onCreate(){
		super.onCreate();
		Log.d(TAG, "create restart service");
	}

}
